package com.example.springbootdemo.filter;

import com.example.springbootdemo.util.JwtTokenUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

/**
 * 认证验证
 * @author H
 * @time 2022/1/31 17:15
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private final RedisTemplate redisTemplate;

    public TokenAuthFilter(AuthenticationManager authenticationManager, RedisTemplate redisTemplate) {
        super(authenticationManager);
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        UsernamePasswordAuthenticationToken auth = getAuthentication(request);
        if (auth != null){
            // 将token中的信息放到security context中用以后续验证
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // 从header中获取token
        String authHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        String authToken;
        if (authHeader != null && authHeader.startsWith("Bearer ")){
            authToken = authHeader.substring(7);
            // 从token中获取用户名
            String username = JwtTokenUtils.getUsernameFromToken(authToken);

            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null){
                // 从redis中获取对应的权限列表
                Set<GrantedAuthority> grantedAuthorities = (Set<GrantedAuthority>) redisTemplate.opsForValue().get(username);

                return new UsernamePasswordAuthenticationToken(username, null, grantedAuthorities);
            }

        }
        return null;
    }
}
